<?php
class search_parser
{
    public static function get_search($querystring=null,$lang='en')
    {
        //XPATHS
        $searchXpath['title'] = '//div[@id="header"]/h1';
        $searchXpath['description'] = '//div[@id="main"]/div[@class="leftright"]/div';
        $searchXpath['movies'] = '//table[@class="results"]/tr[@class]';
        $searchXpath['next'] = '//span[@class="pagination"]';
        $searchXpath['num'] = '//div[@id="left"]';
        $searchXpath['sorter'] = '//table[@class="results"]//th';


        if($querystring == null)
            $querystring = str_replace("udnsearch=1","",$_SERVER['QUERY_STRING']);

        if(strpos($querystring,"&title_type=") === false)
            $querystring.="&title_type=feature,tv_movie,tv_series,tv_special,mini_series,documentary,game,short,video,unknown";

        if(strpos($querystring,"count=") === false)
            $querystring.= "&count=10";

        $imdburl = "http://www.imdb.com/search/title?$querystring";


//prepare DOMDocument
        $html = new DOMDocument();
        @$html->loadHTML(udnutil::read_url($imdburl));
        $xpath = new DOMXPath( $html );

//DATA INFO
        $search['title'] = search_parser::clean(search_parser::getFirstNode($xpath, $searchXpath['title']));
        $search['title'] = str_replace("TV Series/Videos/Feature Films/Short Films/Documentaries/Unknown Works/Video Games/Mini-Series/TV Movies/TV Specials","Movies", $search['title']);
        $search['description'] = search_parser::clean(search_parser::getFirstNode($xpath, $searchXpath['description']));
        $search['number'] = search_parser::clean(search_parser::getFirstNode($xpath, $searchXpath['num']));

        //PAGINATION
        $search['next'] = search_parser::getHtml($xpath, $searchXpath['next']);
        $search['next'] = str_replace('href="/search/title?','href="transform?udnsearch=1&', $search['next']);

        //SORTER
        $search['sorter'] = search_parser::getHtml($xpath, $searchXpath['sorter']);
        $search['sorter'] = str_replace("<th","<div", $search['sorter']);
        $search['sorter'] = str_replace("</th","</div", $search['sorter']);
        $search['sorter'] = str_replace('href="?','href="transform?udnsearch=1&', $search['sorter']);
        $search['sorter'] = str_replace('US Release Date','Date', $search['sorter']);


//cleanup using regex patterns for ids
        $patterns[0] = '/title/';
        $patterns[1] = '/name/';
        $patterns[2] = '/genre/';
        $patterns[3] = '/\//';

//DATA IMAGES
        $searchsList = search_parser::parse($xpath, $searchXpath['movies']);
        $i = 0;
        $search['results'] = array();
        foreach($searchsList as $mov)
        {
            //relative query children
            $search['results'][$i]['order'] = search_parser::clean(udnutil::getNodeValue($xpath,'td[@class="number"]', $mov));
            $search['results'][$i]['poster'] = (udnutil::scaleImdbImage(udnutil::getNode($xpath,'td[@class="image"]/a/img',$mov)->getAttribute("src"),2));
            $search['results'][$i]['small_poster'] = (udnutil::smallImdbImage(udnutil::getNode($xpath,'td[@class="image"]/a/img',$mov)->getAttribute("src")));
            $search['results'][$i]['original_poster'] = (udnutil::originalImdbImage(udnutil::getNode($xpath,'td[@class="image"]/a/img',$mov)->getAttribute("src")));


            $search['results'][$i]['movieid'] = search_parser::clean(preg_replace($patterns,'', $xpath->query('td[@class="title"]/a',$mov)->item(0)->getAttribute("href")));
            $search['results'][$i]['title'] = search_parser::clean($xpath->query('td[@class="title"]/a',$mov)->item(0)->nodeValue);
            $search['results'][$i]['year'] = search_parser::clean($xpath->query('td[@class="title"]/span[@class="year_type"]',$mov)->item(0)->nodeValue);
            $search['results'][$i]['urltitle'] = str_replace(' ', '-', $search['results'][$i]['title']).'-'.$search['results'][$i]['year'];


            $search['results'][$i]['rating'] = search_parser::clean($xpath->query('.//span[@class="rating-rating"]/span[@class="value"]',$mov)->item(0)->nodeValue);
            $search['results'][$i]['description'] = search_parser::clean($xpath->query('.//span[@class="outline"]',$mov)->item(0)->nodeValue);


            $creditsList = $xpath->query('td[@class="title"]/span[@class="credit"]/a',$mov);
            $ci = 0;
            $credits = array();
            foreach($creditsList as $credit)
            {
                $credits[$ci]['id'] = search_parser::clean(preg_replace($patterns,'', $credit->getAttribute("href")));
                $credits[$ci]['name'] = search_parser::clean($credit->nodeValue);
                $ci++;
            }

            $search['results'][$i]['credits'] = $credits;

            $genresList = $xpath->query('td[@class="title"]/span[@class="genre"]/a',$mov);
            $gi = 0;
            $genres = array();
            foreach($genresList as $genre)
            {
                $genres[$gi]['id'] = search_parser::clean(preg_replace($patterns,'', $genre->getAttribute("href")));
                $genres[$gi]['name'] = search_parser::clean($genre->nodeValue);
                $gi++;
            }
            $search['results'][$i]['genres'] = $genres;

            $search['results'][$i]['runtime'] = $xpath->query('.//span[@class="runtime"]',$mov)->item(0)->nodeValue;

            $i++;
        }
        $search['count'] = count($search['results']);

        if($lang == 'ar')
        {
            $search['title'] = lang::translate($search['title']);
        }

        return $search;
    }
    //FUNCTIONS
    public static function parse($xpath, $tag)
    {
        $nodelist = $xpath->query($tag);
        return $nodelist;
    }

    public static function getFirstNode($xpath, $tag)
    {
        $nodelist = search_parser::parse($xpath, $tag);
        return $nodelist->item(0)->nodeValue;
    }

    public static function parseAttribute($xpath, $tag, $attribute)
    {
        $nodelist = search_parser::parse($xpath, $tag);
        if ($nodelist->length > 0) {
            //echo $nodelist->item(0)->nodeValue.$nodelist->item(0)->getAttribute($attribute)."<br />";
            return $nodelist->item(0)->getAttribute($attribute);
        } else
            return "";
    }
    public static function getHtml($xpath,$tag)
    {
        $result_object = udnutil::getNode($xpath, $tag);
        $newdoc = new DOMDocument;
        if($result_object)
        {
            $node = $newdoc->importNode($result_object, true);
            $newdoc->appendChild($node);
            return $newdoc->saveHTML();
        }
        else
            return "";

    }
    function clean($value)
    {
        //$content = htmlspecialchars($value);
        return preg_replace("/[\n\r]/","",$value);
    }
}
?>